﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Interfaces;
using System.IO;

namespace SLAU_FileDAO
{
    public class FileDAO : IDAO
    {
        public string SystemFile { get; set; }
        public string SolutionFile { get; set; }
        public int RoundDecimals { get; set; }

        public FileDAO(string system_file, string solution_file)
        {
            if (system_file == null || solution_file == null)
            {
                throw new ArgumentNullException();
            }
            this.RoundDecimals = 5;
            this.SystemFile = system_file;
            this.SolutionFile = solution_file;
        }

        public SLAU.SLAU LoadSLAU()
        {
            if (!File.Exists(this.SystemFile))
            {
                throw new FileNotFoundException();
            }

            string[] lines = File.ReadAllLines(this.SystemFile);

            int dimension = int.Parse(lines[0]);
            double[,] matr = new double[dimension, dimension];
            double[] free = new double[dimension];

            for (int k = 1; k < dimension+1; k++)
            {
                string line = lines[k];

                double[] int_line = line.Split(' ').Select((elem) => (double.Parse(elem))).ToArray();

                for (int i = 0; i < dimension; i++)
                {
                    matr[k-1, i] = int_line[i];
                }
                free[k-1] = int_line[dimension];
            }

            return new SLAU.SLAU(new SLAU.Matrix(matr), new SLAU.Vector(free));
        }

        public void SaveSolution(SLAU.Vector solution)
        {
            if (solution == null)
            {
                throw new ArgumentNullException();
            }

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < solution.Length; i++)
            {
                sb.AppendFormat(" {0}", Math.Round(solution[i],this.RoundDecimals));
            }
            File.WriteAllText(this.SolutionFile, sb.ToString());
        }


    }
}
